/*
 * LinkDAO.java
 *
 * Created on 25 luty 2007, 14:09
 *
 */

package arocms.business;

import arocms.util.HibernateUtil;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;

/**
 *
 * @author arek
 */
public class LinkDAO implements DaoMethods<Link>{
    
    public Logger log = Logger.getLogger(LinkDAO.class);
    
    /** Creates a new instance of LinkDAO */
    public LinkDAO() {
    }
    
    public Link createOrUpdate(Link aLink) {
        //why it happens that id is not null in case of creation?
        //is it because a hidden field in a LinkForm exists?
        if (aLink.getId()==null || aLink.getId()==0) return create(aLink);
        else return update(aLink);
    }
    
    public Link find(Long pk) {
        log.debug("--> find");
        Session ses = HibernateUtil.getSessionFactory().getCurrentSession();
        ses.beginTransaction();
        Link aLink = (Link) ses.load(Link.class, pk);
        ses.getTransaction().commit();
        log.debug("<-- find");
        return aLink;
    }
    
    public List<Link> findAll() {
        log.debug("--> findAll");
        Session ses = HibernateUtil.getSessionFactory().getCurrentSession();
        ses.beginTransaction();
        List<Link> test = (List<Link>) ses.createQuery("From Link").list();
        log.debug("<-- findAll");
        return test;
    }
    
    public List<Link> findAll(int page, int results_per_page) {
        throw new RuntimeException("LinkDAO: 62");
    }
    
    /**
     * @return A newly created link with set identifier in DETACHED state.
     */
    public Link create(Link aLink){
        log.debug("-> create");
        aLink.setId(null); //i dont know why??
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.persist(aLink);
        session.getTransaction().commit();
        log.debug("<- create");
        return aLink;
    }
    
    /**
     * Commits changes made to a link instance to persistent storage.
     * @return A detached version of a link.
     */
    public Link update(Link aLink){
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();
        s.update(aLink);
        s.getTransaction().commit();
        return aLink;
    }
    
    public boolean delete(Long pk) {
        log.debug("-> delete");
        log.debug("Deleting link with pk = " + pk);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.delete(session.load(Link.class,pk));
        session.getTransaction().commit();
        log.debug("<- delete");
        return true;
    }    

    public boolean delete(Link obj) {
        return delete(obj.getId());
    }
}
